package com.ruoyi.system.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUploadUtil {
    
    private static final String UPLOAD_DIR = "D:/uploads/";
    
    /**
     * 保存上传文件到本地目录
     * @param file MultipartFile对象
     * @param prefix 文件名前缀
     * @return 保存后的File对象
     * @throws IOException 当文件保存失败时抛出
     */
    public static File saveUploadedFile(MultipartFile file, String prefix) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成唯一文件名（前缀+原始文件名）
        String originalFilename = file.getOriginalFilename();
        String savedFilename = prefix + UUID.randomUUID() + "_" + originalFilename;
        Path destination = uploadPath.resolve(savedFilename);
        
        // 保存文件
        file.transferTo(destination.toFile());
        
        return destination.toFile();
    }
    
    /**
     * 清理上传目录
     */
    public static void cleanUploadDir() throws IOException {
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (Files.exists(uploadPath)) {
            Files.walk(uploadPath)
                 .filter(Files::isRegularFile)
                 .forEach(path -> {
                     try {
                         Files.delete(path);
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 });
        }
    }
}